package org.bpms.controller.admin;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.bpms.interceptor.WebInterceptor;
import org.bpms.model.admin.Srole;
import org.bpms.model.admin.Suser;
import org.bpms.plugins.bjui.BjuiRender;
import org.bpms.service.admin.LogService;
import org.bpms.service.admin.RoleService;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Enhancer;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Redis;

/**
 * 后台角色控制器
 * @author hupei
 *
 */
@Clear(WebInterceptor.class)
public class RoleController extends Controller {
	private RoleService roleService = Enhancer.enhance(RoleService.class);
	private LogService  logService = Enhancer.enhance(LogService.class);
	/**
	 * 默认角色管理首页
	 */
	public void index(){
		Map<String,Object> pagemap = new HashMap<String, Object>();
		Integer pageNumber = getParaToInt("pageCurrent", 1);//要访问第几页，默认1
		Integer pageSize = getParaToInt("pageSize", 15);//每页多少条数据，默认15
		String orderField = getPara("orderField", "id");//对什么字段排序，默认空字符串
		String orderDirection = getPara("orderDirection", "asc");//升序还是降序，默认升序
		String roleid = getPara("id");
		String  text   = getPara("text", null);
		roleService.findRoleFromMenu(roleid, text, pageNumber, pageSize,
				orderField, orderDirection, pagemap);
		setAttr("page",pagemap);
		setAttr("id", roleid==null?"":roleid);
		setAttr("text", text==null?"":text);
		render("/admin/role/role.html");
	}
	
	/**
	 * 保存角色和菜单的关系
	 */
	public void roleMenuSave(){
		String menus = getPara("menus");
		String roleId = getPara("roleid");
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> jsonmap = new HashMap<String , Object>();	
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		Map map = null;
		try {
			map = mapper.readValue(menus, Map.class);
			if (null != map){
				roleService.updateMenuRelation(map, roleId);
			}
		} catch (IOException e) {
			render(BjuiRender.error("保存失败！" , false));
			e.printStackTrace();
		}
		render(BjuiRender.success("保存成功！" , false));
	}
	
	/**
	 * 保存角色和用户的关系
	 */
	public void roleUserSave(){
		String users = getPara("users");
		String roleId = getPara("roleid");
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> jsonmap = new HashMap<String , Object>();	
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		Map map = null;
		try {
			map = mapper.readValue(users, Map.class);
			if (null != map){
				roleService.updateUserRelation(map, roleId);
			}
		} catch (IOException e) {
			render(BjuiRender.error("保存失败！" , false));
			e.printStackTrace();
		}
		render(BjuiRender.success("保存成功！" , false));
	}
	
	/**
	 * 批量保存角色
	 */
	public void save(){
		Map<String, String[]> map = getParaMap();
		String [] ids = map.get("id");
		String [] texts = map.get("text");
		if (null != ids && ids.length > 0){
			for (int i = 0 ; i < ids.length ; i++){
				Srole role = new Srole();
				if (null == ids[i] || ids[i].equals("")){
					role.set("text", texts[i]);
				}else{
					role.set("text", texts[i])
					           .set("id", ids[i]);
				}
				roleService.saveOrUpdate(role);
			}
			String sessionId = getCookie("adminsession");
			Suser user = Redis.use().get(sessionId);
			logService.create(user.getStr("username"), "批量保存角色");
		}
		render(BjuiRender.success("保存成功！" , false));
	}
	
	/**
	 * 获取拥有该菜单的角色
	 */
	public void roleFromMenu(){
		Map<String,Object> pagemap = new HashMap<String, Object>();
		Integer pageNumber = getParaToInt("pageCurrent", 1);//要访问第几页，默认1
		Integer pageSize = getParaToInt("pageSize", 15);//每页多少条数据，默认15
		String orderField = getPara("orderField", "id");//对什么字段排序，默认空字符串
		String orderDirection = getPara("orderDirection", "asc");//升序还是降序，默认升序
		String menuid = getPara("menuid");
		roleService.findRoleFromMenu(menuid, pageNumber, pageSize, 
				orderField, orderDirection, pagemap);
		setAttr("menuid", menuid);
		setAttr("page",pagemap);
		render("/admin/menu/menu_getrole.html");
	}
	
	/**
	 * 删除角色
	 */
	public void remove(){
		String roleId = getPara("roleid");
		Srole role = roleService.findById(roleId);
		String sessionId = getCookie("adminsession");
		Suser user = Redis.use().get(sessionId);
		logService.create(user.getStr("username"), "删除角色:"+role.getStr("text"));
		roleService.delRole(roleId);
		render(BjuiRender.success("删除成功！" , false));
	}
}
